package com.red.servlet.house;

import com.red.entity.House;
import com.red.service.impl.HouseServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@WebServlet(name = "HouseQueryServlet", value = "/houseQuery")

public class HouseQueryServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        House[] houses;
        String[] status = req.getParameterValues("status");
        // 分页状态
        HashMap<String, Integer> pageInfo = new HashMap<>();
        int curPage = 1;
        int size = 8;
        int pages;

        // page 参数检查
        if (req.getParameter("page") != null) {
            curPage = Integer.parseInt(req.getParameter("page"));
            if (curPage < 0) {
                resp.getWriter().print("无效 page 参数");
                return;
            }
        }

        // size 参数检查
        if (req.getParameter("size") != null) {
            size = Integer.parseInt(req.getParameter("size"));

            if (size < 0 || size > 50) {
                resp.getWriter().print("无效 size 参数");
                return;
            }
        }

        // status 参数检查
        if (status != null) {
            houses = new HouseServiceImpl().getHouses(size, curPage, status);
        } else {
            houses = new HouseServiceImpl().getHouses(size, curPage);
        }

        pages = (int)Math.ceil(new HouseServiceImpl().getSize(status) / (double)size);

        // 打包分页信息
        pageInfo.put("curPage", curPage);
        pageInfo.put("pages", pages);
        req.setAttribute("pageInfo", pageInfo);

        if (req.getParameter("mode") != null) {
            int mode = Integer.parseInt(req.getParameter("mode"));
            req.setAttribute("queryResult", houses);

            switch (mode) {
                case 1:
                    req.getRequestDispatcher("jsp/main.jsp").forward(req, resp);
                    break;
                case 2:
                    req.getRequestDispatcher("jsp/manage/house_list.jsp").forward(req, resp);
                    break;
                default:
                    resp.getWriter().print("不存在该查询模式");
            }
        } else {
            resp.getWriter().print("你想查啥？");
        }
    }
}
